package org.voyager.service.admin.upload;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.voyager.common.beans.JsonResult;

import com.aliyun.oss.OSS;

@RestController
@RequestMapping("/upload")
public class UploadController {

	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
	
	private final String IMAGE = "jpg|gif|png|jpeg|bmp";
	
	@Autowired
    private OSS ossClient;
	@Value("${oss.bucketName}")
	private String bucketName;
	
	@PostMapping("/image")
	public JsonResult uploadImage(@RequestParam("file") MultipartFile file) {
		if (file != null) {
			// 验证图片
			if (!this.isImage(file.getOriginalFilename())) {
				logger.warn("非图片格式，上传失败");
				return JsonResult.error("非图片格式，上传失败");
			}
			try {
				String key = "images/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "-" + file.getOriginalFilename();
				ossClient.putObject(bucketName, key, file.getInputStream());
				// 设置URL过期时间为100年  3600l* 1000*24*365*100
				Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
				URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
				logger.info("上传成功，url：" + url);
				return JsonResult.ok("上传成功").putData("url", url);
			} catch (Exception e) {
				logger.error("上传失败" + e);
				return JsonResult.error("上传失败");
			}
		} else {
			logger.warn("上传文件不能为空");
			return JsonResult.error("上传文件不能为空");
		}
	}
	
	private boolean isImage(String fileName) {
		return IMAGE.contains(StringUtils.substringAfterLast(fileName, ".").toLowerCase());
	}
	
}
